<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-form-item label="类型" prop="type">
        <el-select v-model="formItem.type" filterable remote placeholder="请选择类型" @change="typeChange">
          <el-option v-for="(item) in typeList" :key="item.code" :label="item.text" :value="item.code" />
        </el-select>
      </el-form-item>
      <el-form-item label="值班人" prop="sourceUserName">
        <el-input v-model="formItem.sourceUserName" placeholder="请选择值班" :disabled="true">
          <!-- <el-button slot="append" icon="el-icon-search" @click="handleDutyIconClick" /> -->
        </el-input>
      </el-form-item>
      <el-form-item label="值班日期" prop="sourceUserName">
        <el-button icon="el-icon-search" @click="handleDutyIconClick">选择值班日期</el-button>
        <!-- <el-input v-model="formItem.sourceUserName" placeholder="请选择值班" :disabled="true">
        </el-input> -->
      </el-form-item>
      <el-form-item label="值班开始时间" prop="startTime">
        <el-date-picker v-model="formItem.startTime" type="datetime" placeholder="请选择值班" align="right" :disabled="true" />
      </el-form-item>
      <el-form-item label="值班结束时间" prop="endTime">
        <el-date-picker v-model="formItem.endTime" type="datetime" placeholder="请选择值班" align="right" :disabled="true" />
      </el-form-item>
      <el-form-item label="换班人" prop="targetUserName">
        <el-input v-model="formItem.targetUserName" placeholder="请选择换班人" @focus="handleUserIconClick">
          <!-- <el-button v-if="formItem.type === 'shift'" slot="append" icon="el-icon-search" @click="handleShiftIconClick" /> -->
        </el-input>
      </el-form-item>
      <el-form-item v-if="formItem.type === 'shift' && formItem.targetUserName" label="换班日期" prop="targetUserName">
        <el-button v-if="formItem.type === 'shift' && formItem.targetUserName" icon="el-icon-search" @click="handleShiftIconClick">选择替换班日期</el-button>
      </el-form-item>
      <el-form-item v-if="formItem.type === 'shift'" label="换班开始时间" prop="shiftStartTime">
        <el-date-picker v-model="formItem.shiftStartTime" type="datetime" placeholder="请选择换班" align="right" :disabled="true" />
      </el-form-item>
      <el-form-item v-if="formItem.type === 'shift'" label="换班结束时间" prop="shiftEndTime">
        <el-date-picker v-model="formItem.shiftEndTime" type="datetime" placeholder="请选择换班" align="right" :disabled="true" />
      </el-form-item>
    </el-form>
    <SelectDialog v-if="dutySelDialogFormVisible" title="选择值班" :append-to-body="true" :show="dutySelDialogFormVisible" @on-ok="selectDutyOk" @on-cancel="selectDutyCancel">
      <DutyForm ref="dutysTable" :for-selection="true" :multiple-selected="true" />
    </SelectDialog>
    <SelectDialog v-if="userSelDialogFormVisible" title="选择换班人" :append-to-body="true" :show="userSelDialogFormVisible" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersTable" :for-selection="true" :multiple-selected="true" :org-code="formItem.orgCode" />
    </SelectDialog>
    <SelectDialog v-if="shiftSelDialogFormVisible" title="选择换班" :append-to-body="true" :show="shiftSelDialogFormVisible" @on-ok="selectShiftOk" @on-cancel="selectShiftCancel">
      <DutyForm ref="shiftTable" :for-selection="true" :multiple-selected="true" :is-user="false" :user-name="formItem.targetUserCode" />
    </SelectDialog>
  </div>
</template>

<script>
import {
  create,
  update,
  detail
} from '@neu/dcom-ui/api/shift'
import UsersPage from '@neu/auth-ui/views/users/tables'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import DutyForm from './dutyForm'
import { list } from '@neu/dcom-ui/api/dictionary'
import { dutyInfo } from '@neu/dcom-ui/api/teamgroup'
import { getInfo } from '@neu/biz-core/api/user'

// 定义一个表单原始项
const formItem = {
  /** 源人员名称 */
  sourceUserName: '',
  /** 源人员编码 */
  sourceUserCode: '',
  /** 开始时间 */
  startTime: null,
  /** 结束时间 */
  endTime: null,
  /** 开始时间 */
  shiftStartTime: null,
  /** 结束时间 */
  shiftEndTime: null,
  /** 替班人员名称 */
  targetUserName: '',
  /** 替班人员编码 */
  targetUserCode: '',
  /** 组织名称 */
  orgName: '',
  /** 组织代码 */
  orgCode: '',
  /** 值班安排ID */
  dutyArrangementId: null,
  /** 类型 */
  type: 'shift'
}
export default {
  name: 'ShiftEditForm',
  components: {
    SelectDialog,
    UsersPage,
    DutyForm
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      typeList: [],
      // 换班人弹窗
      userSelDialogFormVisible: false,
      // 值班记录弹窗
      dutySelDialogFormVisible: false,
      // 换班弹窗
      shiftSelDialogFormVisible: false,
      // 表单验证规则
      rules: {
        sourceUserName: [{
          required: true,
          message: '值班选择不能为空',
          trigger: 'blur'
        }],
        targetUserName: [{
          required: true,
          message: '换班人不能为空',
          trigger: 'blur'
        }],
        type: [{
          required: true,
          message: '类型不能为空',
          trigger: 'blur'
        }],
        startTime: [{
          required: true,
          message: '开始时间不能为空',
          trigger: 'blur'
        }],
        endTime: [{
          required: true,
          message: '结束时间不能为空',
          trigger: 'blur'
        }],
        shiftStartTime: [{
          required: true,
          message: '换班开始时间不能为空',
          trigger: 'blur'
        }],
        shiftEndTime: [{
          required: true,
          message: '换班结束时间不能为空',
          trigger: 'blur'
        }]
      },
      modal: true
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        this.fetch()
      },
      immediate: true
    }
  },
  created() {
    list({ 's_type': 'ShiftType' }).then(res => {
      this.typeList = res.data
    })
    dutyInfo().then(res => {
      this.formItem.orgCode = res.data[0] ? res.data[0].orgCode : ''
    })
    getInfo().then(res => {
      this.formItem.sourceUserCode = res.data.username
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
        this.formItem.sourceUserName = this.$store.getters.name
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    /** 人员选择弹窗 */
    handleUserIconClick() {
      this.userSelDialogFormVisible = true
    },
    /** 换班选择弹窗 */
    handleShiftIconClick() {
      this.shiftSelDialogFormVisible = true
    },
    /** 类型变化 */
    typeChange(val) {
      if (val === 'substitute') {
        this.formItem.shiftStartTime = null
        this.formItem.shiftEndTime = null
      }
    },
    /** 换班人选择确认 */
    selectUserOk() {
      var users = this.$refs.usersTable.selections
      if (users.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个用户',
          type: 'error'
        })
      }

      if (users.length < 1) {
        this.formItem.shiftStartTime = null
        this.formItem.shiftEndTime = null
        this.formItem.targetUserName = ''
        this.formItem.targetUserCode = ''
      } else {
        if (users[0].username === this.formItem.sourceUserCode) {
          return this.$message({
            showClose: true,
            message: '不能选择本人',
            type: 'error'
          })
        }
        this.formItem.shiftStartTime = null
        this.formItem.shiftEndTime = null
        this.formItem.targetUserName = users[0].name
        this.formItem.targetUserCode = users[0].username
      }
      this.userSelDialogFormVisible = false
    },
    /** 换班人选择取消 */
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    handleDutyIconClick() {
      this.dutySelDialogFormVisible = true
    },
    // 值班选择确认
    selectDutyOk() {
      var dutys = this.$refs.dutysTable.selections
      if (dutys.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一条值班记录',
          type: 'error'
        })
      }

      if (dutys.length < 1) {
        this.formItem.startTime = null
        this.formItem.endTime = null
        this.formItem.dutyArrangementId = null
      } else {
        this.formItem.startTime = new Date(dutys[0].startTime)
        this.formItem.endTime = new Date(dutys[0].endTime)
        this.formItem.dutyArrangementId = dutys[0].dutyArrangementId
      }
      this.dutySelDialogFormVisible = false
    },
    // 值班选择取消
    selectDutyCancel() {
      this.dutySelDialogFormVisible = false
    },
    // 换班选择确认
    selectShiftOk() {
      var dutys = this.$refs.shiftTable.selections
      if (dutys.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一条换班记录',
          type: 'error'
        })
      }

      if (dutys.length < 1) {
        this.formItem.shiftStartTime = null
        this.formItem.shiftEndTime = null
        // this.formItem.dutyArrangementId = null
      } else {
        this.formItem.shiftStartTime = new Date(dutys[0].startTime)
        this.formItem.shiftEndTime = new Date(dutys[0].endTime)
        // this.formItem.dutyArrangementId = dutys[0].dutyArrangementId
      }
      this.shiftSelDialogFormVisible = false
    },
    // 换班选择取消
    selectShiftCancel() {
      this.shiftSelDialogFormVisible = false
    },
    reset() {
      this.$refs.myform.resetFields()
    }
  }
}
</script>
